/**
 * Created by W on 2017/3/20.
 */
/**
 * Created by Brant on 2016/12/28.
 * 案件动态
 */
module.exports = function ($rootScope, $scope, $state,$stateParams, $cookies, teamService, paginationService, calendarService,$window) {
  $rootScope.showCaseDiv = false;

    //取出当前用户头像
    $scope.userPortraitSave=$cookies.get('userPortraitSave');

  /*初始化tab切换*/
  $scope.tabShow = 0;
  $scope.alertTabShow = 0;
  $scope.leftActive = 0;
  $scope.getFirm = getFirm;
  $scope.teamList = teamList;
  $scope.lawfirm = lawfirm;
  $scope.getTeamMember = getTeamMember;
  $scope.teamUpdate = teamUpdate;
  $scope.changeTab = changeTab;
  $scope.invitePerson = invitePerson;
  $scope.teamCreate = teamCreate;
  $scope.teamAssign = teamAssign;
  $scope.teamRemove = teamRemove;
  $scope.editTeam = editTeam;
  $scope.closeTeam = closeTeam;
  $scope.showEditTeam = showEditTeam;
  $scope.showDeleteTeam = showDeleteTeam;
  $scope.showQuitTeam = showQuitTeam;
  $scope.addMember = addMember;
  $scope.successInvite = successInvite;
  $scope.teamSkip = teamSkip;
  $scope.showCaseType = showCaseType;
  $scope.setCookieId = setCookieId;
  $scope.teamPerType = teamPerType;
  $scope.lawPerType = lawPerType;
  $scope.searchCaseList = searchCaseList;
  $scope.searchLawCaseList = searchLawCaseList;
  $scope.lawCaseList = lawCaseList;
  $scope.invitePersonSingle = invitePersonSingle;
  $scope.clearPara = clearPara;
  $scope.searchLawfirmMember = searchLawfirmMember;
  $scope.addTeamMemberFromLawfirm = addTeamMemberFromLawfirm;
  $scope.createT = createT;

  $scope.inviteStep = 1;
  $scope.userId = kbt.decrypt($cookies.get('cookieUserId'));
  //分页
  $scope.pageSetting = paginationService.getDefaultPageSetting();
  $scope.pageSetting2 = paginationService.getDefaultPageSetting();
  //团队案件分页
  $scope.pageSetting3 = paginationService.getDefaultPageSetting();
  $scope.pageSetting4 = paginationService.getDefaultPageSetting();

  //删除团队成员
  $scope.deleteTeamMember = deleteTeamMember;


  $scope.getPersonSingle = getPersonSingle;
  $scope.inviterEmailSingle = '';
  // 默认选择我的律所，true：律所；false:团队
  $scope.lawFirmTeamFlag = true;
  $scope.teamLawFrimName = "";

  // 平台用户计数
  $scope.oldUserInviteCount = 0;
  // 非平台用户计数
  $scope.newUserInviteCount = 0;
  // 平台用户邮件
  $scope.inviteOldMembers = [];
  // 非平台用户邮件
  $scope.inviteNewMembers = [];
  // 临时存储查询的用户信息
  $scope.invitedTempMembers = [];
  // 邀请成功后，存储用户信息
  $scope.invitedMembers = [];
  // 日程所选用户
  $scope.selectedUsers = [];
  // 律所右侧用户列表
  $scope.lawList = [];
  // 有冲突 ，待定功能
  $scope.lawList2 = [];
  // 团队右侧用户列表
  $scope.teamlawList = [];
  // 律所内添加成员数量
  $scope.teamlawfirmcount = 0;
  // 全局请求变量
  $scope.pageGlobalPara = new Object();


  $scope.w5cValidatorInviteProvider = {
    blurTrig   : false,
    showError  : false,
    removeError: true
  };

  // 清空页面内部分参数
  function clearPara() {
    // 平台用户计数
    $scope.oldUserInviteCount = 0;
    // 非平台用户计数
    $scope.newUserInviteCount = 0;
    // 平台用户邮件
    $scope.inviteOldMembers = [];
    // 非平台用户邮件
    $scope.inviteNewMembers = [];
    // 临时存储查询的用户信息
    $scope.invitedTempMembers = [];
    // 邀请成功后，存储用户信息
    $scope.invitedMembers = [];
    // 邀请输入框
    $scope.inviterEmailSingle = "";
    // 检索参与律师
    $scope.CaseLawyerTianSelectSub =[];
    //从律所邀请输入框
    $scope.inviteLawfrimMemberText = "";
    $scope.inviteLawfrimMemberList = "";
  }

  //初始化页面
  function init() {
    // getFirm();
    teamList($scope.leftActive);
    // lawfirm();
    $('.delTeam').show();
    //点击空白处关闭

    $(document).click(function () {
      setTimeout(function(){
        // $('#showCre').css('display','block !important');
        // $('#showed').hide();
        // $scope.isShowCreate = true;
      },300)

    });
  }
  init();
$scope.showInvit =function(){
  $scope.phoneEmpty = false;
  $scope.phoneValid = false;
  $scope.inviteNewMembers = [];
  $scope.invitedMembers = [];
  $scope.inviteLawfrimList =[];
  $scope.inviteLawfrimMemberList =[];
}
  //控制判断左侧点击律所还是团队，true = 团队  false = 律所 根据判断来显示日程日历
  $scope.teamOff = false;

  //获取左侧律所数据
  function getFirm(id,team) {
    clearPara();
    $scope.lawFirmTeamFlag = true;
    $scope.teamLawFrimName = "test";
    $scope.teamId='';
  	$scope.tabShow = 0;
  	if(team || team == undefined){
  		$scope.teamOff = false;

  	}
    $scope.leftActive = id;

    teamService.queryUser().then(function (response) {
      if(response.data.code == 1){
        $scope.leftLow = response.data.data;
        $scope.leftActive = $scope.leftLow.lawfirmid;
        lawCaseList();
        if($scope.leftLow.authState!=2){
          if($scope.leftTeam[0]){
            getTeamMember(0,$scope.leftTeam[0].id)
          }

        }
      }
    });

    $scope.pageGlobalPara.id = id;
    $scope.pageGlobalPara.team = team;
  }

  //团队左侧列表
  function teamList(id) {
    $scope.leftActive = id;
    teamService.teamList().then(function (response) {
      if(response.data.code == 1){
        $scope.leftTeam = response.data.data;
        // if($scope.leftTeam.length==0){
          getFirm()
        // }else{
        //   getTeamMember(0,$scope.leftTeam[$scope.leftTeam.length-1].id);
        // }
      }
    });
  }

  function createT(){
    $scope.inviteStep =1;
    $scope.clearDef();


  }

  $scope.clearDef = function(){
    $scope.create = {
      name:'',
      description:''
    }
    $scope.addMemList = {
      userName:''
    }
     $scope.chooseList = [];
    $scope.searchList = [];
  }


  //获取律所成员
  function lawfirm() {
    if($scope.tabShow==0){
      var params = {'pageNum': $scope.pageSetting.pageNo, 'pageSize': $scope.pageSetting.pageSize}
      teamService.lawfirm(params).then(function (response) {

        if(response.data.code == 1){
          //律所
          var data = response.data.data;
          $scope.lawMemLen = data.length;
          $scope.lawList = data;

        }
      });
    }
  }

  function getTeamMemberList() {
    var params = {'pageNum': $scope.pageSetting2.pageNo, 'pageSize': $scope.pageSetting2.pageSize,'id':$scope.leftActive};
    teamService.getTeamMember(params).then(function (response) {

      if(response.data.code == 1){
        //团队
        var data = response.data.data;
        $scope.lawList2 = data;
      }
    });
  }

  //搜索团队案件
  function searchCaseList() {
    $scope.pageSetting3 = paginationService.getDefaultPageSetting();
    getTeamMember(1,$scope.leftActive);
  }
  //搜索律所案件
  function searchLawCaseList() {
    $scope.pageSetting4 = paginationService.getDefaultPageSetting();
    lawCaseList();
  }

  //获取团队成员
  function getTeamMember(index, id,team,num) {
    $scope.teamId = id;
    $scope.tabShow= 0;
      clearPara();
      $scope.lawFirmTeamFlag = false;

      if(num == 0){
          //日程 第几个团队管理
          $scope.teamMemberIndex = 0;
      }else{
          $scope.teamMemberIndex = num || $scope.teamMemberIndex
      }
      if(team){
          $scope.teamOff = true;
      }
      if(id != null) {
          $scope.leftActive = id;
      }else{
        $scope.tabShow = 0;
      }
      if(index==0) {
          $scope.tabShow = 0;
          getTeamMemberList()
      } else if(index==1){
          $scope.tabShow = 1;
          if($scope.leftActive == $scope.leftLow.lawfirmid){
            getFirm($scope.leftLow.lawfirmid,1);
          }else{
            var params = {'teamId':$scope.leftActive,'caseName':$scope.caseName,'pageNum': $scope.pageSetting3.pageNo, 'pageSize': $scope.pageSetting3.pageSize}
            teamService.teamCaseList(params).then(function (response) {
              if(response.data.code == 1){
                $scope.castList = response.data.data;
                $scope.pageSetting3.totalItems = response.data.totalCount;
              }
            });
          }
      }else if(index == 2){
          // getTeamMemberList()
          $scope.tabShow = 2;
          if($scope.teamOff){
            lawfirm()
            calendarInit(2)
            $scope['init2' + 2]();
          }else{
            calendarInit()
            $scope.init2();
          }

      }else if(index == 3){
          $scope.tabShow=3;
          getTeamMemberList();
          for(var i = 0; i<$scope.leftTeam.length; i++){
            if($scope.leftTeam[i].id == $scope.leftActive){
              $scope.updateTeam = $scope.leftTeam[i];
            }
          }
          for(var i=0; i<$scope.leftTeam.length; i++){
            if($scope.leftTeam[i].id == $scope.leftActive){
              $scope.owner = $scope.leftTeam[i].owner;
            }
          }
      }

      $scope.pageGlobalPara.index = index;
      $scope.pageGlobalPara.id = id;
      $scope.pageGlobalPara.team = team;
      $scope.pageGlobalPara.num = num;
  }

  //律所的案件
  function lawCaseList() {
    if($scope.tabShow == 0) {
      lawfirm();
    }
    if($scope.tabShow == 1){
      var params = {'caseName':$scope.caseLawName,'pageNum': $scope.pageSetting4.pageNo, 'pageSize': $scope.pageSetting4.pageSize};
      teamService.lawCaseList(params).then(function (response) {
        if(response.data.code == 1){
          $scope.castLawList = response.data.data;
          $scope.pageSetting4.totalItems = response.data.totalCount;
        }
      });
    }
  }

  //修改案件类型
  function showCaseType(num) {
    var arr1 = ['民','刑','行','仲'];
    return arr1[num-1];
  }

  //案件跳转案件详情
  function setCookieId(item) {
    $cookies.put('caseAppId', item.id);
    $cookies.put('caseAppName', item.casename);
    $('#Bar li').removeClass('active');
    $('#Bar li').eq(1).addClass('active');
    $state.go('caseBarDetailxia');
  }


  //团队人员状态
  function teamPerType(num) {
    switch (num){
      case 1:
        return '已加入';
        break;
      case 3:
        return '已邀请';
        break;
      case 4:
        return '已退出';
        break;
      case 7:
        return '拒绝';
        break;
      case 9:
        return '已删除';
        break;
    }
  }
  //律所人员状态
  function lawPerType(num) {
    if (num <= 2) {
      return '已加入';
    } else if (num > 2) {
      return '邀请中';
    }
  }

  //更新团队信息
  function teamUpdate() {
    if($scope.tabShow==3) {
      $scope.updateTeam.id=$scope.leftActive;
      teamService.teamUpdate($scope.updateTeam).then(function (response) {
        if(response.data.code == 1){
          //团队
          // teamList($scope.leftActive);
        }
      });
    }
  }

  function changeTab(index) {
    if(index==0) {
      $scope.tabShow = 0;
      getTeamMember();
    } else if(index==1){
      $scope.tabShow = 1;
    }else if(index == 2){
      $scope.tabShow = 2;
    }else if(index == 3){
      $scope.tabShow=3;
      for(var i = 0; i<$scope.leftTeam.length; i++){
        if($scope.leftTeam[i].id == $scope.leftActive){
          $scope.updateTeam = $scope.leftTeam[i];
        }
      }
    }
  }
$scope.assFlo = true;

  //转让团队
  function teamAssign() {
    var params = {
      id:$scope.leftActive,
      assignId:$scope.teamLawList.userId
    };
    teamService.teamAssign(params).then(function (response) {
      if(response.data.code == 1){
        $('#myModalPrompt').modal('hide');
        $scope.teamMsg = response.data.msg;
        $('#myModalDissolution').modal('show');
        teamList($scope.leftActive);
        // $scope.$watch('owner',function(newValue,oldValue, scope){
        //
        // }, true);
      }else{
        $scope.teamMsg = response.data.msg;
        $('#myModalPrompt').modal('hide');
        $('#myModalDissolution').modal('show')
      }
    });
  }
  //确定取消的confirm
  function confirmBtn(content, func) {
    $scope.teamMsg = content;
    $("#myModalDelete").modal('show');
    if(typeof(func) == 'function') {
      $("#ok_btn").on("click", func);
    }
  }
  $scope.showeditteam = false;
  $scope.isShowCreate = true;
  $scope.team={};
  //显示团队编辑框
  function showEditTeam(index,item) {
    $scope.showeditteam = true;
    $scope.isShowCreate = false;
    $scope.team.id = item.id;
    $scope.team.teamName = item.teamname;
    $scope.team.teamDescription =item.teamdescription;
  };
  function closeTeam(){
    $scope.showeditteam = false;
    $scope.isShowCreate = true;
  }



  //编辑团队
  function editTeam(item) {
    var params = {
      id:item.id,
      name:item.teamName,
     description:item.teamDescription
    };
    teamService.teamUpdate(params).then(function (response) {
      if(response.data.code == 1){
        $scope.showeditteam = false;
        $scope.isShowCreate = true;
        $scope.teamMsg = response.data.msg;
        teamList($scope.leftActive);
      }
    });


  };
  //解散团队
  function teamRemove(index,item) {
    var params = {
      id:item.id
    };
    bootbox.dialog({
      message: "确定删除此团队",
      title: "提示信息",
      buttons: {
        Cancel: {
          label: "取消",
          // className: "btn-default",
          className: "btn-cancel",
          // confirmButtonColor: "#DD6B55",
          callback: function () {

          }
        },
        OK: {
          label: "确定",
          // className: "btn-default",
          className: "btn-confirm",
          // confirmButtonColor: "#DD6B55",
          callback: function () {
            teamService.teamRemove(params).then(function (response) {
              if(response.data.code == 1){
                $scope.teamMsg = response.data.msg;
                teamList($scope.leftActive);
              }
            });
          }
        }
      }
    });

  };

  //解散团队
  function teamClearn() {
    var params = {
      id:$scope.leftActive
    };
    teamService.teamRemove(params).then(function (response) {
      if(response.data.code == 1){
        $('#myModalDelete').modal('hide');
        $('#myModalDissolution').modal('show');
        $scope.teamMsg = response.data.msg;
        teamList($scope.leftActive);
      }
    });
  };

  //退出团队
  function teamQuit() {
    var params = {
      id:$scope.leftActive
    };
    teamService.teamQuit(params).then(function (response) {
      if(response.data.code == 1){
        $('#myModalDelete').modal('hide');
        $('#myModalDissolution').modal('show');
        $scope.teamMsg = response.data.msg;
        teamList($scope.leftActive);
        getTeamMember(0,$scope.leftTeam[0].id);
        $scope.leftActive = $scope.leftTeam[0].id;
      }
    });
  };

  function showDeleteTeam(index,item) {
    var str = "您确定要解散当前团队吗";
    confirmBtn(str, teamClearn);
  }
  function showQuitTeam() {
    var str = "您确定要退出当前团队吗";
    confirmBtn(str, teamQuit);
  }


  //创建团队
  function teamCreate() {
    if($scope.create.name==""){
      bootbox.dialog({
        ///size: "small",
        title: "提示信息",
        message: "团队名称不能为空",
        className:'d-promptBox',
        buttons: {
          OK: {
            label: "确定",
            className: "d-btn-confirm5",
          }
        },
        callback: function(){ /* your callback code */ }
      });
      return false;
    }
    teamService.teamCreate($scope.create).then(function (response) {
      if(response.data.code == 1){
        $scope.inviteStep = 2;//邀请成员
        $scope.newAddId = response.data.data;

        getTeamMember(0,$scope.newAddId);
        teamList($scope.leftActive);
        //getTeamMember(0,$scope.leftTeam[$scope.leftTeam.length-1].id);
      }
    });
  }


  //成员删除
  function deleteTeamMember(event,index,id,type) {
    event.stopPropagation();
    var params = {
      'teamId':$scope.teamId,
      'memberId':id,
      'type':type
    };
    bootbox.dialog({
      message: "确定删除此成员吗?",
      title: "删除成员",
      className:'d-promptBox',
      buttons: {
        OK: {
          label: "确定",
          className: "d-btn-confirm",
          callback: function () {
            teamService.teamMemberRemove(params).then(function (data) {
              if(data.data.code == 1){
                for(var index1 = 0; index1 < $scope.leftTeam.length; index1++) {
                  if($scope.teamId == $scope.leftTeam[index1].id) {
                    $scope.leftTeam[index1].memberSize = $scope.leftTeam[index1].memberSize - 1;
                  }
                }
                $scope.lawList2.splice(index,1);
                // //刷新左侧列表
                // teamList();
                // getTeamMember();
              }
            })
          }
        },
        Cancel: {
          label: "取消",
          className: "d-btn-cancel",
          style:'background:red',
          callback: function () {

          }
        }

      }
    });

  }


$scope.searchMember = searchMember;
  $scope.chooseMember = chooseMember;
  $scope.cancelChoose = cancelChoose;
  $scope.searchList = [];
  $scope.chooseList = [];
  function searchMember(){
    if($scope.addMemList.userName!=""){
      teamService.addMember($scope.addMemList).then(function (response) {
        if(response.data.code == 1){
          if(response.data.data.length){
            $scope.searchList=response.data.data;
            var tempList=[];
            angular.forEach($scope.searchList,function(data,index){
              if($scope.chooseList.length >0){
                angular.forEach($scope.chooseList,function(data2,index2){
                  if(data.id != data2.id){
                    tempList.push(data)
                  }
                });
              } else {
                tempList.push(data)
              }
              $scope.searchList=tempList;
            });

          }else{
            $scope.searchList=[];
          }

        }
      })
    }else{
      $scope.searchList = [];
    }
  }
  function chooseMember(item,index){
    $scope.chooseList.push(item);
    $scope.searchList.splice(index,1);
    item.show = !item.show;
  }


  function cancelChoose(item,index){
    $scope.chooseList.splice(index,1);
    $scope.searchList.push(item);
    item.show = !item.show;
  }



  //添加成员
   $scope.creatNameList = [];//检索数组
   $scope.chooseName=[];//选中的数组
   $scope.nameList = [];//显示的数组
  function addMember() {
    if($scope.addMemList.userName!=""){
      teamService.addMember($scope.addMemList).then(function (response) {


        if(response.data.code == 1){
          var dataN = response.data.data;
          // for(var m=0; m<dataN.length; m++){
          //   if($scope.chooseName.length){
          //     for(var n =0;n<$scope.chooseName.length;n++){
          //       if($scope.chooseName[n].id === dataN[m].id ){
          //
          //         dataN.splice(dataN[m]);
          //       }
          //     }
          //   }else{
          //     $scope.creatNameList.push(dataN[m]);
          //   }
          // }
          $scope.creatNameList = dataN;
        }
      });
    }else{
      $scope.creatNameList = [];
    }
  }



  //选中名字
  $scope.chooseNameFun=function (item) {
    item.show = !item.show;
  if($scope.chooseName.length){
    $scope.chooseName.map(function(citem){
      if(citem['id'] === item['id']){
        return;
      }else {
        $scope.chooseName.push(item);
        for(var i=0; i<$scope.creatNameList.length; i++){
         if($scope.creatNameList[i].id == item.id){
           $scope.creatNameList.splice(item,1)
         }
        }
      }
    })
  }else {
    $scope.chooseName.push(item);
    for(var i=0; i<$scope.creatNameList.length; i++) {
      if ($scope.creatNameList[i].id == item.id) {
        $scope.creatNameList.splice(item,1);
      }
    }
  }


  };

  $scope.deleteNameFun = function(item,index){

    $scope.chooseName.splice(index,1);
    $scope.creatNameList.push(item);
    item.show = !item.show;
    // for (var i=0;i<$scope.chooseName.length;i++){
    //   if($scope.chooseName[i].id == item.id){
    //     $scope.chooseName.splice(i);
    //      $scope.creatNameList.push(item);
    //     item.show = !item.show;
    //
    //   }
    // }

  }


  //邀请成员
  $scope.invite = {};
  function invitePerson() {
    // 校验
    $scope.inviteForm.doValidate('inviterEmail');
    if($scope.inviteForm.$errors.length > 0)
      return;
    //拼id
    var str = '';
    var creatList = $scope.chooseList;
    for(var i=0;i<creatList.length; i++){
      if(creatList[i].show == true && creatList[i].show!=undefined){
        str+=(creatList[i].id+',');
      }
    }


      if(($scope.invite.inviterEmail == undefined || $scope.invite.inviterEmail == "") && str==""){
          bootbox.dialog({
            ///size: "small",
            title: "提示信息",
            message: "请填写邀请人或直接跳过此步骤",
            className:'d-promptBox',
            buttons: {
              OK: {
                label: "确定",
                className: "d-btn-confirm5",
              }
            },
            callback: function(){ /* your callback code */ }
          });
          return false;
      }

    $scope.invite.id = $scope.newAddId;
    $scope.invite.inviterId = str;
    teamService.teamInvite($scope.invite).then(function (response) {
      if(response.data.code == 1){
        $scope.inviteStep = 3;
        $scope.inviteResult = response.data.data;
      }
    });

  }

  //完成邀请
  function successInvite() {
    $scope.inviteStep = 1;
    $scope.create.name = '';
    $scope.create.description = '';
    //刷新左侧列表
    $scope.teamList();
    $scope.leftActive = $scope.leftTeam[$scope.leftTeam.length-1].id;
    // $scope.getTeamMember();
    getTeamMember(0,$scope.newAddId);
    $scope.addMemList = {};
    $scope.invite = {};
    $scope.creatNameList = [];
    $scope.inviteResult.invited=[];
  }

  //跳过此步
  function  teamSkip() {
    $scope.inviteStep = 3;
  }

  // 团队新建完成后，查询成员
  function getPersonSingle() {
    $scope.invitedTempMembers = [];
    // 后台请求参数
    $scope.invite = [];
    $scope.invite.id = $scope.leftActive;
    $scope.invite.inviterEmail = $scope.inviterEmailSingle;
    $scope.invite.type = $scope.lawFirmTeamFlag?1:2;

    teamService.teamGetMemberSingleUrl($scope.invite).then(function (response) {
      if(response.data.code == 1){
        $scope.invitedTempMembers = response.data.data;
      }
    });

  }

  // 团队新建完成后，添加成员
  function invitePersonSingle(email) {
      // 后台请求参数
      $scope.invite = {
        // id:$scope.leftActive,
        // inviterEmail:email,
        // type:$scope.lawFirmTeamFlag?1:2
      };
      $scope.invite.id = $scope.leftActive;
      $scope.invite.inviterEmail = email;
      $scope.invite.type = $scope.lawFirmTeamFlag?1:2;

      teamService.teamInviteMemberSingleUrl($scope.invite).then(function (response) {
          if(response.data.code == 1){
              $scope.inviteStep = 3;
              // $scope.invitedCount=response.data.data.invited.length;
              // $scope.newUserInviteCount=response.data.data.inviting.length;
              if (response.data.data.invited != undefined && response.data.data.invited.length != 0 ) {
                  // 老用户
                  // $scope.inviteOldMembers.push(response.data.data);
                  // $scope.oldUserInviteCount = $scope.inviteOldMembers.length;
                  $scope.invitedMembers.push(response.data.data.invited);
              } else if (response.data.data.inviting != undefined && response.data.data.inviting.length != 0 ){
                // 新用户
                $scope.inviteNewMembers.push(response.data.data.inviting);

              }

              // 清空这次用户信息
              $scope.invitedTempMembers = [];
              $scope.inviterEmailSingle = "";

              // 追加团队计数
              if ($scope.invite.type == 2)
                for(var index1 = 0; index1 < $scope.leftTeam.length; index1++) {
                  if($scope.leftActive == $scope.leftTeam[index1].id) {
                    $scope.leftTeam[index1].memberSize = $scope.leftTeam[index1].memberSize + 1;
                  }
                }
          } else {

              // 清空这次用户信息
              $scope.invitedTempMembers = [];
              $scope.inviterEmailSingle = "";
          }
      });
  }



  //根据姓名、邮箱。电话搜索律所成员
  function searchLawfirmMember() {
    // if($scope.inviteLawfrimMemberText) {
      var params = {
        text: $scope.inviteLawfrimMemberText,
        teamId: $scope.leftActive
      };
      teamService.searchLawfirmMember(params).then(function (response) {
        if (response.data.code == 1) {
          $scope.inviteLawfrimMemberList = response.data.data;
        }
      })
    // }
  }
$scope.inviteLawfrimList = [];
  //从律所添加团队成员
  function addTeamMemberFromLawfirm(member) {
    if(member) {
      var params = {
        id: $scope.leftActive,
        inviterId: member.id
      }
      teamService.teamInvite(params).then(function (response) {

        if (response.data.code == 1) {

          $scope.teamlawfirmcount = $scope.teamlawfirmcount + 1;
          member.invited = true;
          member.flag = 3;
          $scope.inviteLawfrimList.push(response.data.data);
        }
      })
    }

  }

	//我的律所日程日历相关逻辑 初始化
	//calendarInit()
	//我的团队日程日历相关逻辑 初始化
	//calendarInit(2)
	function calendarInit(num){

	  // 强制删除上次检索列表
    $(".join-per-p").on("click", function () {
      $scope.CaseLawyerTianSelectSub = [];
      $scope.$apply();
      $scope.cellphone = "";
      // $("#addXieZhuInput2").val("");
      // $(".LawyerboxUl").addClass("hide");
      $(".LawyerAddBody3").removeClass("hide");
    });
    $(".LawyerAddBody3 .Add-close").on("click", function () {
      $scope.CaseLawyerTianSelectSub = [];
      $scope.$apply();
      $scope.cellphone = "";
      // $("#addXieZhuInput2").val("");
      // $(".LawyerboxUl").addClass("hide");
      $(".LawyerAddBody3").addClass("hide");
    });

		var objNumBer = '';

    // 选择的用户
    $scope.selectedUsers = [];

		if(num || num == 0){
			objNumBer = num;
		}

		$scope['init2' + objNumBer] = function () {

          // 清空日程
          $('#calendar' + objNumBer).fullCalendar( 'removeEventSource',$scope.textcad);
          $scope.textcad = [];
          $('#calendar' + objNumBer).fullCalendar( 'addEventSource', $scope.textcad);
          $scope.teamlawList= [];

          // //上来先隐藏提示框
	        // $("#textcontent" + objNumBer).hide();
          //上来先隐藏提示框
          $("#textcontent").hide();

	        //取出当前用户头像路径
	        $scope.userPortrait=$cookies.get('userPortraitSave');

	        //取出当前用户名字
	        $scope.userPortraitName=$cookies.get('userPortraitName');

	        //设置自己的头像
	        $scope.settingusertext = portraitsetting($scope.userPortrait,$scope.userPortraitName);

	        /*登录ID*/
	        $scope.loginId = kbt.decrypt($cookies.get('cookieUserId'));

	        /*设置默认添加的日程颜色为红色*/
	        $scope.taskcolour = "red";

	        /*保存日程对象*/
	        var myCalEvent=new Object();

	        $scope.testclick = function () {

	            $("#myModal" + objNumBer).modal("show");
	        };

      // $scope.tasknewlist($scope.loginId);
          // 团队ID
          $scope.tasknewlist($scope.leftActive);

	        /*新建日程添加参与人存放数组*/
	        $scope.cyList = new Array();



	        jQuery(function ($) {
	            /*新建日程-设置颜色*/
	            $("#task-red" + objNumBer).click(function () {
	                $scope.taskcolour = "red";
	            });
	            $("#task-purple" + objNumBer).click(function () {
	                $scope.taskcolour = "purple";
	            });
	            $("#task-blue" + objNumBer).click(function () {
	                $scope.taskcolour = "blue";
	            });
	            $("#task-green" + objNumBer).click(function () {
	                $scope.taskcolour = "green";
	            });
	            /*编辑日程-设置颜色*/
	            $("#edit-task-red" + objNumBer).click(function () {
	                $scope.taskcolour = "red";
	            });
	            $("#edit-task-purple" + objNumBer).click(function () {
	                $scope.taskcolour = "purple";
	            });
	            $("#edit-task-blue" + objNumBer).click(function () {
	                $scope.taskcolour = "blue";
	            });
	            $("#edit-task-green" + objNumBer).click(function () {
	                $scope.taskcolour = "green";
	            });
	        })

	    };


	    /**
	     * 日期选择器
	     */
	    $(".form_datetime").datetimepicker({
	        format: 'yyyy-mm-dd hh:ii:ss',
	        language: "zh-CN",
	        charset: "utf-8",
	        startView: 2,
	        weekStart: 1,
	        //todayBtn:  1,
          autoclose: "day",
          todayHighlight: 1,
          forceParse: "day",
	        //showMeridian: 1
	    });

	    /**
	     * 更改日期事件
	     */
	    $('.form_datetime')
	        .datetimepicker()
	        .on('changeDate', function () {
	            //$('.form_datetime').datetimepicker('hide');
	        });

	    /**
	     * 日程列表
	     * @param id
	     */
	    $scope.tasknewlist = function (id) {
	        teamService.teamtasklist(id,$scope.selectedUsers, $scope.leftActive).then(function (data) {
	            $rootScope.loadingShow = false;
	            $rootScope.fadeShow = false;
	            if (data.code == 1) {
	                setlist(data.data);
	                if ($scope.teamlawList.length < 1)
                    $scope.teamlawList= data.datamember;
	            }
	        }, function (response) {
	            $rootScope.loadingShow = false;
	            $rootScope.fadeShow = false;
	            console.error('gaintaklist error', response.status, response.statusText);
	        });
	    };

	    /**
	     * 新增日程任务
	     * @param result1 日程标题
	     * @param taskcolour 日程颜色
	     * @param timenow 开始时间
	     * @param timefinish 结束时间
	     * @param calendar 日历对象
	     * @param userIds 参与人ID
	     */
	    $scope.uploadingtask = function (result1, taskcolour, timenow, timefinish, calendar, userIds) {
	        $rootScope.loadingShow = true;
	        $rootScope.fadeShow = true;


	        calendarService.establishtask(result1, taskcolour, timenow, timefinish, $scope.loginId, userIds, $scope.userPortraitName, 2, "", "", $scope.leftActive).then(function (data) {
	            $rootScope.loadingShow = false;
	            $rootScope.fadeShow = false;
	            if (data.code == 1) {
                  var taskTemple = {
                    title: result1,
                    start: timenow,
                    end: timefinish,
                    color: taskcolour,
                    editable: false,
                    id:data.workScheduleId,
                  };
	                //本地添加日程
	                // calendar.fullCalendar('renderEvent', taskTemple, true // make the event "stick"
	                // );

                  $('#calendar' + objNumBer).fullCalendar( 'removeEventSource',$scope.textcad);
                  $scope.textcad.push(taskTemple);
                  $('#calendar' + objNumBer).fullCalendar( 'addEventSource', $scope.textcad);
	                //重新加载列表
	                // $scope.tasknewlist($scope.leftActive);
	                //parent.document.location.reload();
	                //  calendar.fullCalendar('renderEvent')
	                $scope.cyList.splice(0,$scope.cyList.length);

	                var memberList;
	                // //取消日程 律所/团队 成员勾选
	                // if($scope.lawList2 || $scope.lawList){
                    //
	                // 		$scope.teamOff ? memberList = $scope.lawList2 : memberList = $scope.lawList
	                // 		if(memberList){
	                // 			for (var i = 1; i < memberList.length; i++) {
			         //        		if(memberList[i].check == true){
			         //        			memberList[i].check = false;
			         //        		}
			         //        }
	                // 		}
                    //
	                // }

	                $("#calendar-new" + objNumBer).modal("hide");


	            }
	        }, function (response) {

	            $rootScope.loadingShow = false;
	            $rootScope.fadeShow = false;
	            console.error('updatemessage error', response.status, response.statusText);
	        });

	    };


	    /**
	     * 增加时间
	     * @param date
	     * @param minutes
	     * @returns {Date}
	     */
	    function addMinutes(date, minutes) {
	        minutes = parseInt(minutes);
	        var interTimes = minutes * 60 * 1000;
	        interTimes = parseInt(interTimes);
	        return new Date(Date.parse(date.replace(/\-/g, "/")) + interTimes);
	    }


	    /**
	     * 设置日历
	     * @param data
	     */
	    function setlist(data) {
	        var tasklistarray = [];
	        for (var i = 0; i < data.length; i++) {
	            var task = new Object();
	            task.title = data[i].schedule;
	            task.start = data[i].beginTime;
	            task.end = data[i].endTime;
	            task.color = data[i].colour;
	            task.id = data[i].id;
	            task.editable = false;
	            tasklistarray.push(task);
	        }
          $scope.textcad = tasklistarray;

	        //判断现在是律所还是团队，并返回相关数据

	        // if($scope.teamOff){
	        // 		 $scope.textcad = returnTextcasData($scope.teamMemberIndex)
	        // }else{
	        // 		 $scope.textcad = returnTextcasData2()
	        // }

	        //正常ajax请求数据 时恢复
//	        $scope.textcad =tasklistarray;

	        jQuery(function ($) {
	            $('#external-events div.external-event' + objNumBer).each(function () {
	                // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
	                // it doesn't need to have a start or end 它不需要有一个开始或结束
	                var eventObject = {
	                    title: $.trim($(this).text()) // use the element's text as the event title 使用元素的文本事件标题
	                };

	                // store the Event Object in the DOM element so we can get to it later 将事件对象存储在DOM元素我们可以得到它
	                $(this).data('eventObject', eventObject);

	                // make the event draggable using jQuery UI 可拖动的使用jQuery UI事件
	                $(this).draggable({
	                    zIndex: 999,
	                    revert: true,      // will cause the event to go back to its 将导致事件回到它的?
	                    revertDuration: 0  //  original position after the drag 原始位置后的阻力?
	                });

	            });

	            var date = new Date();
	            $('#calendar' + objNumBer).fullCalendar('destroy')
	            var calendar = $('#calendar' + objNumBer).fullCalendar({
	                //isRTL: true,
	                //firstDay: 1,// >> change first day of week

	                buttonHtml: {
	                    prev: '<i class="ace-icon fa fa-chevron-left"></i>',
	                    next: '<i class="ace-icon fa fa-chevron-right"></i>'
	                },

	                header: {
	                    left: 'prev,today,next',
	                    center: 'title',
	                    right: 'month,agendaDay'
	                },
					        monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
	              	monthNamesShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
	              	dayNames: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
	              	dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
	              	today: ["今天"],
		              firstDay: 1,
		              buttonText: {
		                  today: '本月',
		                  month: '月',
		                  week: '周',
		                  day: '日',
		                  prev: '上一月',
		                  next: '下一月'
		              },
	                events: $scope.textcad,

	                timeFormat: 'HH:mm',

	                theme:false,
	                slotLabelFormat:"HH:mm",
	                slotDuration:'00:15:00',// 日视图插槽间隔
	                allDaySlot:true,//是否显示全天
	                editable: true,
	                droppable: true, // this allows things to be dropped onto the calendar !!!
	                drop: function (date) { // this function is called when something is dropped

	                    // retrieve the dropped element's stored Event Object
	                    var originalEventObject = $(this).data('eventObject');
	                    var $extraEventClass = $(this).attr('data-class');


	                    // we need to copy it, so that multiple events don't have a reference to the same object
	                    var copiedEventObject = $.extend({}, originalEventObject);

	                    // assign it the date that was reported
	                    copiedEventObject.start = date;
	                    copiedEventObject.allDay = false;
	                    if ($extraEventClass) copiedEventObject['className'] = [$extraEventClass];

	                    // render the event on the calendar
	                    // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
	                    $('#calendar' + objNumBer).fullCalendar('renderEvent', copiedEventObject, true);

	                    // is the "remove after drop" checkbox checked?
	                    if ($('#drop-remove' + objNumBer).is(':checked')) {
	                        // if so, remove the element from the "Draggable Events" list
	                        $(this).remove();
	                    }

	                }
	                ,
	                selectable: true,
	                selectHelper: true,

	                /**
	                 * 新建日程
	                 * @param date
	                 * @param calEvent
	                 * @param start
	                 * @param end
	                 * @param allDay
	                 */
	                select: function (date, calEvent, start, end, allDay) {
                      var hour = null;
                      var min = null;
                      if (date._i != undefined) {
                        hour = date._i[3];
                        min = date._i[4];
                      }

                      var date = new Date(date);
                      if ( hour != null) {
                        date.setHours(hour);
                        date.setMinutes(min);
                      }

	                    $("#calendar-new" + objNumBer).modal("show");

	                    $("#input_text1" + objNumBer).val("");
	                    $('#my-count' + objNumBer).text(0);
	                    $scope.taskcolour = "red";

	                    $("#calendar-details-new" + objNumBer).val(date.pattern("yyyy-MM-dd HH:mm:ss"));

	                    $("#button_text1" + objNumBer).unbind('click').click(function () {

	                        var result1 = $("#input_text1" + objNumBer).val();

	                        var timenow = $("#calendar-details-new" + objNumBer).val();

	                        var timefinish = addMinutes(timenow, 15).pattern("yyyy-MM-dd HH:mm:ss");

	                        if (result1 !== "") {
	                            /*参与人ID*/
	                            var userIds = "";
	                            for (var i=0;i<$scope.cyList.length;i++){
	                                if(i!=$scope.cyList.length-1){
	                                    userIds +=$scope.cyList[i].userId+"!%!";
	                                }else{
	                                    userIds +=$scope.cyList[i].userId;
	                                }
	                            }
	                            //请求网络上传日程
	                            $scope.uploadingtask(result1, $scope.taskcolour, timenow, timefinish, calendar, userIds);

	                        } else {
	                            //如果没有标题就提示一下
	                            $("#textcontent" + objNumBer).show();
	                        }

	                    });
                      $("#textcontent" + objNumBer).hide();
	                    //提示消息取消的按钮
	                    $("#textcontent" + objNumBer).unbind('click').click(function () {
	                        $("#textcontent" + objNumBer).hide();
	                    });
	                }
	                ,
	                /**
	                 * 编辑日程
	                 * @param calEvent
	                 */
	                eventClick: function (calEvent) {
	                    myCalEvent = calEvent;

	                    /*获取当前处于哪个视图*/
	                    var view = $('#calendar' + objNumBer).fullCalendar('getView');

	                    /*如果当前视图是日视图,则隐藏查看详情按钮;如果当前视图是月视图,则显示查看详情按钮*/
	                    if (view.name == 'agendaDay') {
	                        $('#calendarDetailEdit' + objNumBer).hide();
	                    } else if (view.name == 'month') {
	                        $('#calendarDetailEdit' + objNumBer).show();
	                    }

	                    /*设置任务标题*/
	                    $('#calendar-task-title' + objNumBer).val(calEvent.title);
	                    $('#my-count-edit' + objNumBer).text(calEvent.title.length);
	                    /*设置任务时间*/
	                    $('#calendar-details-timeval' + objNumBer).val(calEvent.start._i);
	                    /*显示弹出框*/
	                    $('#calendar-details' + objNumBer).modal('show');
	                    /*查询日程参与人*/
	                    $scope.queryWorksCheduleParticipant(calendar, calEvent);

	                    /*更新操作*/
	                    $scope.updateTask = function () {
	                        $scope.updateCalendar(calendar, calEvent);
	                    };

	                    /*删除操作*/
	                    $scope.deleteTask = function () {
	                        $scope.deleteCalendar(calendar, calEvent);
	                    };

	                    /*查看详情*/
	                    $scope.turnDetails = function () {
	                    		var newData = calEvent.start._i.replace(/\-/g, "/")
	                        //跳转日视图
	                        calendar.fullCalendar('changeView', 'agendaDay');
	                        //跳转点击哪天的视图
	                        calendar.fullCalendar('gotoDate', new Date(newData));
	                        //隐藏弹出框
	                        $('#calendar-details' + objNumBer).modal('hide');
	                    };

	                }

	            });

	        });


	        /**
	         * 编辑日程-删除日程任务
	         */
	        $scope.deleteCalendar = function (calendar, calEvent) {
	            $rootScope.loadingShow = true;
	            $rootScope.fadeShow = true;
	            calendarService.deleteCalendar(calEvent.id,$scope.userPortraitName,$scope.loginId).then(function (data) {
	                $rootScope.loadingShow = false;
	                $rootScope.fadeShow = false;
	                if (data.code == 1) {
	                    calendar.fullCalendar('removeEvents', function (ev) {
	                        return (ev._id == calEvent._id);
	                    });
	                    //隐藏弹出框
	                    $('#calendar-details' + objNumBer).modal('hide');
	                }
	            }, function (response) {
	                $rootScope.loadingShow = false;
	                $rootScope.fadeShow = false;
	                console.error('deleteCalendar error', response.status, response.statusText);
	            });

	        };

	        /**
	         * 编辑日程-更新日程任务
	         */
	        $scope.updateCalendar = function (calendar, calEvent) {


	            $rootScope.loadingShow = true;
	            $rootScope.fadeShow = true;

	            calEvent.title = $('#calendar-task-title' + objNumBer).val();
	            calEvent.color = $scope.taskcolour;
	            calEvent.start = $('#calendar-details-timeval' + objNumBer).val();
	            calEvent.end = addMinutes(calEvent.start, 15).pattern("yyyy-MM-dd HH:mm:ss");
	            calendarService.updateCalendar(calEvent.id, calEvent.title, calEvent.start, calEvent.end, calEvent.color, $scope.loginId).then(function (data) {
	                $rootScope.loadingShow = false;
	                $rootScope.fadeShow = false;
	                if (data.code == 1) {

	                    //calendar.fullCalendar('updateEvent', calEvent);

	                    //重新获取日程
	                    $scope.tasknewlist($scope.leftActive);
	                    //隐藏弹出框
	                    $('#calendar-details' + objNumBer).modal('hide');
	                }
	            }, function (response) {
	                $rootScope.loadingShow = false;
	                $rootScope.fadeShow = false;
	                console.error('updateCalendar error', response.status, response.statusText);
	            });

	        };

	        /**
	         * 编辑日程-查询日程参与人
	         */
	        $scope.queryWorksCheduleParticipant = function (calendar, calEvent) {
	            $rootScope.loadingShow = true;
	            $rootScope.fadeShow = true;
	            calendarService.queryWorksCheduleParticipant(calEvent.id).then(function (data) {
	                $rootScope.loadingShow = false;
	                $rootScope.fadeShow = false;
	                if (data.code == 1) {
	                    $scope.lawerList = data.data;
	                }
	            }, function (response) {
	                $rootScope.loadingShow = false;
	                $rootScope.fadeShow = false;
	                console.error('queryWorksCheduleParticipant error', response.status, response.statusText);
	            });

	        };

	    }

      /**
       * 新建任务时检索律师
       */
      $scope.addXieZhuInputEnter = function () {
          if ($scope.cellphone != '') {
              $rootScope.loadingShow = true;
              $rootScope.fadeShow = true;

              calendarService.CaseLawyerTian($scope.cellphone, 2, "", "", $scope.leftActive).then(function (data) {
                  $('.LawyerboxUl').show();
                  $('.LawyerboxUl').css("height", "100px");
                  $('.LawyerAddBody3').css("min-height", "230px");
                  if (data.code == 1) {
                      $scope.CaseLawyerTianSelectSub = data.data;
                      $scope.CaseLawyerTianButton = function (name, LawyerId) {
                        calendarService.updateWorksCheduleParticipant(myCalEvent.id, LawyerId, 3, $scope.userPortraitName, $scope.loginId).then(function (data) {
                          $rootScope.loadingShow = false;
                          $rootScope.fadeShow = false;
                          if (data.code == 1) {
                            bootbox.alert({
                              size: "small",
                              title: "提示信息",
                              message: "添加成功，耐心等待参与人确认",
                              callback: function(){ /* your callback code */ }
                            });
                            $(".LawyerAddBody3").addClass('hide');
                          }
                        }, function (response) {
                          $rootScope.loadingShow = false;
                          $rootScope.fadeShow = false;
                          console.error('updateWorksCheduleParticipant error', response.status, response.statusText);
                        });
                      };
                      //点击关闭
                      $scope.CaseLawyerClose = function () {
                        $scope.CaseLawyerTianModel = "";
                      };
                      $(".LawyerboxUlbutton").show()
                      $('#error-text' + objNumBer).hide();
                  } else {
                    $('#error-text' + objNumBer).show();
                    $scope.CaseLawyerTianSelectSub = [];
                    $(".LawyerboxUlbutton").hide()
                  }
                  $rootScope.loadingShow = false;
                  $rootScope.fadeShow = false;
              }, function () {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
              });
          } else {
            $scope.CaseLawyerTianSelectSub = [];
          }
      }

      /**
       * 编辑任务时检索律师
       */
      $scope.addCanyuInputEnter = function () {
          if ($scope.cellphone != '') {
              $rootScope.loadingShow = true;
              $rootScope.fadeShow = true;
              calendarService.CaseLawyerTian($scope.cellphone, 2, "", "", $scope.leftActive).then(function (data) {
                $('.LawyerboxUl').show();
                $('.LawyerboxUl').css("height", "100px");
                $('.LawyerAddBody3').css("min-height", "230px");
                $scope.CaseLawyerTianSelectSub = [];
                if (data.code == 1) {
                  $scope.CaseLawyerTianSelectSub = data.data;
                  //点击关闭
                  $scope.CaseLawyerClose = function () {
                    $scope.CaseLawyerTianModel = "";
                  };
                  $(".LawyerboxUlbutton").show();
                  $('#error-add-text' + objNumBer).hide();
                } else {
                  $(".LawyerboxUlS").html("未搜索到结果");
                  $scope.CaseLawyerTianSelectSub = [];
                  $(".LawyerboxUlbutton").hide();
                  $('#error-add-text' + objNumBer).show();
                }
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
              }, function () {
                $rootScope.loadingShow = false;
                $rootScope.fadeShow = false;
              });
          } else {
            $scope.CaseLawyerTianSelectSub = [];
          }
      }

	    /**
	     * 编辑日程-删除日程参与人
	     * @param LawyerId 参与人ID
	     * @constructor
	     */
	    $scope.CaseLawyerDel = function (LawyerId) {

	        calendarService.updateWorksCheduleParticipant(myCalEvent.id, LawyerId,9,$scope.userPortraitName,$scope.loginId).then(function (data) {
	            $rootScope.loadingShow = true;
	            $rootScope.fadeShow = true;
	            if (data.code == 1) {
	                $scope.queryWorksCheduleParticipant(calendar,myCalEvent);
	            }
	        }, function (response) {
	            $rootScope.loadingShow = false;
	            $rootScope.fadeShow = false;
	            console.error('updateWorksCheduleParticipant error', response.status, response.statusText);
	        });
	    };

	    /**
	     * 新建日程-添加参与人
	     * @param name
	     * @param LawyerId
	     * @constructor
	     */
	    $scope.CanYuTianButton = function (name, LawyerId) {
	        /*避免重复添加*/
	        for (var i=0;i<$scope.cyList.length;i++){
	            if($scope.cyList[i].userId == LawyerId){
	                bootbox.alert({
	                    size: "small",
	                    title: "提示信息",
	                    message: "不能重复添加参与人",
	                    callback: function(){ /* your callback code */ }
	                });
	                return;
	            }
	        }
	        var cyUser = {
	            userName:name,
	            userId:LawyerId
	        };
	        $scope.cyList.push(cyUser);
	        $('.LawyerAddBody3').addClass('hide');
	    };

	    /**
	     * 新建日程-删除参与人
	     * @param name
	     * @param LawyerId
	     * @constructor
	     */
	    $scope.delCanyu = function (LawyerId) {
	    		var memberList;
	        for (var i=0;i<$scope.cyList.length;i++){
	            if($scope.cyList[i].userId == LawyerId){
	                $scope.cyList.splice(i,1);

	                //取消已勾选的成员
	                $scope.teamOff ? memberList = $scope.lawList2 : memberList = $scope.lawList
					for (var i = 0; i < memberList.length; i++) {
	                		if(memberList[i].userId == LawyerId){
	                			memberList[i].check = false;
	                			return
	                		}
	                }

	            }
	        }
	    };

	    $scope.titleLen = 0;
	    $('#input_text1' + objNumBer).bind('input propertychange', function() {
	        $scope.titleLen = $('#input_text1' + objNumBer).val().length;
	        $('#my-count' + objNumBer).text($scope.titleLen);
	    });

	    $scope.titleLenEdit = 0;
	    $('#calendar-task-title' + objNumBer).bind('input propertychange', function() {
	        $scope.titleLenEdit = $('#calendar-task-title' + objNumBer).val().length;
	        $('#my-count-edit').text($scope.titleLenEdit);
	    });

		// /**
	     // * 添加删除日程登记成员
	     // */
		// //团队日程日历添加删除成员
		// $scope.changeMenberCheck = function(index,item){
		// 	var memberObj;
        //
		// 	if($scope.teamOff){
		// 		var userId = item.userId
		// 		var userName = item.userName
		// 		memberObj = $scope.lawList2[index];
		// 	}else{
		// 		var userId = item.id
		// 		var userName = item.username
		// 		memberObj = $scope.lawList[index];
		// 	}
        //
        //
		// 	memberObj.check == undefined ? memberObj.check = true : memberObj.check = !memberObj.check
        //
		// 	if(memberObj.check == true){
		// 		$scope.cyList.push({
		// 			userId : userId,
		// 			userName : userName
		// 		});
		// 	}else{
		// 		for (var i = 0; i < $scope.cyList.length; i++) {
		// 			if($scope.cyList[i].userId == userId){
		// 				$scope.cyList.splice(i,1);
		// 				return
		// 			}
		// 		}
		// 	}
        //
		// }



    /**
     * 选择用户刷新日程列表
     * @param id
     */
    $scope.refleshtasklist = function (id) {

      $rootScope.loadingShow = true;
      $rootScope.fadeShow = true;
      $scope.selectedUsers = [];
      angular.forEach($scope.teamlawList, function (user) {
        if (user.isselect) {
          $scope.selectedUsers.push(user.id);
        }
      });
      teamService.teamtasklist(id, $scope.selectedUsers, $scope.leftActive).then(function (data) {
        $rootScope.loadingShow = false;
        $rootScope.fadeShow = false;
        if (data.code == 1) {
          if ($scope.lawList.length < 1) {
            $scope.lawList = data.datamember;
          }

          var tasklistarray = [];
          if (data.data.length > 0)
            for (var i = 0; i < data.data.length; i++) {
              var task = new Object();
              task.title = data.data[i].schedule;
              task.start = data.data[i].beginTime;
              task.end = data.data[i].endTime;
              task.color = data.data[i].colour;
              task.id = data.data[i].id;
              task.editable = false;
              tasklistarray.push(task);
            }

          $('#calendar' + objNumBer).fullCalendar( 'removeEventSource',$scope.textcad);
          $scope.textcad = tasklistarray;
          $('#calendar' + objNumBer).fullCalendar( 'addEventSource', $scope.textcad);
          // $scope.$apply();
        }
      }, function (response) {
        $rootScope.loadingShow = false;
        $rootScope.fadeShow = false;
        console.error('gaintaklist error', response.status, response.statusText);
      });
      // }
    };
	}

  /**
   * 关闭邀请弹窗
   * @param id
   */
  $scope.closeInviteWin = function () {
    angular.element("#myModalInvitation").modal("hide");
    $scope.alertTabShow = 0;
    $scope.inviterEmailSingle = "";
    $scope.inviteLawfrimMemberText = "";
    $scope.invitedTempMembers = [];
    $scope.inviteLawfrimMemberList = [];
    $scope.teamlawfirmcount = 0;
    $scope.newUserInviteCount = 0;
    if ($scope.teamOff) {
      getTeamMember($scope.pageGlobalPara.index, $scope.pageGlobalPara.id, $scope.pageGlobalPara.team, $scope.pageGlobalPara.num);
    } else {
      getFirm($scope.pageGlobalPara.id, $scope.pageGlobalPara.team);
    }
    // getTeamMember(0,$scope.newAddId);
    //  $scope.teamList();
  }

  //邀请邮箱验证
  //法人手机号码验证
  $scope.phoneEmpty = false;
  $scope.phoneValid = false;
  $scope.invitationEmail = invitationEmail;
  // $scope.checkMobileOrganiza = checkMobileOrganiza;
  function invitationEmail(){
    var phone = $scope.inviterEmailSingle;
    //var myreg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
          var myreg =/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    if(phone == ''){
      $scope.phoneEmpty = true;
      $scope.phoneValid = false;
    }
    // else if(phone.length !=11){
    //   $scope.phoneValid = true;
    // }
    else if(!myreg.test(phone)){
      $scope.phoneValid = true;
      $scope.phoneEmpty = false;
    }else{
      $scope.phoneEmpty = false;
      $scope.phoneValid = false;
    }
    return false;
  }
};
